#!/bin/bash

# incrementally backup $HOME using rsync

SOURCE="$HOME/"
DEST="/media/Dragis_HDD/homebackup/"
KEEP=5 # how many backups besides the current one should be kept
EXCLUDEFROM="$SOURCE/.backup_excludes"
NICENESS=10
LOGFILE="$DEST/.lastbackup.log"

RSYNC_OPTS="-rltHh"
if [[ $1 != '-q' ]]; then
	RSYNC_OPTS="--verbose $RSYNC_OPTS"
fi


if [[ -d "$DEST" ]]; then
	[[ $1 != '-q' ]] && echo "Backing up $SOURCE to $DEST..."

	# remove oldest backup if necessary
	if [[ `ls -d -1 $DEST/backup-* | wc -l` > $KEEP ]]; then
		[[ $1 != '-q' ]] && echo "Removing stale stuff..."
		rm -rf `ls -d -1 $DEST/backup-* | sort -n | head -n1`;
	fi

	rm -f $DEST/current # <- symlink to the newest backup

	NEWEST="`ls -d -1 $DEST/backup-* | sort -n | tail -n1`"
	CURRENT="$DEST/backup-`date +%Y-%m-%d-%H-%M`/"

	nice -n $NICENESS rsync $RSYNC_OPTS --delete --delete-excluded \
	--exclude-from=$EXCLUDEFROM --exclude='.*' --progress \
	--numeric-ids --link-dest=$NEWEST $SOURCE $CURRENT 2> $LOGFILE

	if [ -s $LOGFILE ]; then
		echo "Backup of $SOURCE did not finish successfully. Review the \
log file (${LOGFILE}) to see what went wrong." >&2
		echo "Deleting this partial backup in 5 seconds... Press \
Ctrl-C to abort." >&2
		for i in `seq 5 -1 1`; do
			echo -n "$i " >&2
			sleep 1
		done
		echo >&2 # a happy newline
		rm -rf $CURRENT
		exit 127
	else
		ln -s $CURRENT $DEST/current
		[[ $1 != '-q' ]] && echo "Backup of $SOURCE finished! Woohoo!"
	fi

	# also sync music between home and disk if not included in this backup
	[[ -n `cat $EXCLUDEFROM | grep '\<Music\>'` ]] && syncmusic.sh $1
else
	echo "A backup was scheduled, but $DEST was not found. Please insert the \
disk and run `basename $0`." >&2
	exit 1
fi
